<template>
    <div class="box">
        <div class="form">
            <el-button type="primary" text @click="$router.back()">返回地址列表</el-button>
            <el-form :model="form" label-width="120px">
                <el-form-item label="收货人：">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="手机：">
                    <el-input v-model="form.mobile" />
                </el-form-item>
                <el-form-item label="所在地区：">
                    <el-input v-model="form.area" />
                </el-form-item>
                <el-form-item label="地址：">
                    <el-input v-model="form.address" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitAddress">{{ isEdit ? '修改收货地址' : '保存收货地址' }}</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>

import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex';
import { useRoute } from 'vue-router'

const route = useRoute()
const isEdit = ref(false)   // 是否为修改
const store = useStore()
const form = reactive({
    name: '',   // 收货人
    mobile: '', // 手机
    area: '',   // 所在地区
    address: '', // 地址
})

if (route.query.id) {
    isEdit.value = true
    form.name = route.query.name
    form.mobile = route.query.mobile
    form.area = route.query.area
    form.address = route.query.address
}

const submitAddress = () => {
    if (!form.name || !form.mobile || !form.area || !form.address) return ElMessage.error('不能为空')
    let obj = {
        ...form,
        id: isEdit.value ? route.query.id : new Date().getTime(), // id
        isDefault: isEdit.value ? route.query.isEdit : false    // 是否为默认地址
    }
    if (!isEdit.value) {
        store.commit('add', obj)
        ElMessage.success('添加地址成功')
    } else {
        store.commit('edit', obj)
        ElMessage.success('修改地址成功')
    }
    form.name = form.mobile = form.area = form.address = ''
}

</script>

<style lang="scss" scoped>
.box {
    width: 50%;
    margin: 30px auto;
    border: 1px solid orange;

    .form {
        padding: 20px 10px;
    }
}
</style>